import { defineStore } from "pinia";

import { loginApi, logoutApi } from "@/api/auth";
import { getUserInfo, getButtonInfo, getUnReadMessageApi } from "@/api/user";
import { resetRouter } from "@/router";
import { store } from "@/store";

import { LoginData } from "@/api/auth/types";
import { UserInfo } from "@/api/user/types";

import { useStorage } from "@vueuse/core";
import { useCookies } from "@vueuse/integrations/useCookies";
import { encrypt } from "@/utils/crypto";

export const useUserStore = defineStore("user", () => {
  const user: UserInfo = {
    roles: [], // 预留字段
    perms: [], // 按钮权限集合
  };

  const unRead = ref(0); // 未读消息条数

  const linkId = useStorage("linkId", "", sessionStorage); // 消息需要跳转的ID

  const token = useStorage("loginStorage", "", localStorage);

  const cookies = useCookies(["username", "password"]);

  // 设备类型(是否是Window7桌面)
  const isWindow7 = useStorage("isWindow7", false, sessionStorage);

  // 工厂信息
  const userPlantInfo = useStorage("userPlantInfo", "", localStorage);

  /**
   * 设置工厂信息
   */
  function setUserPlantInfo(data: any) {
    userPlantInfo.value = JSON.stringify(data);
    localStorage.setItem("userPlantInfo", userPlantInfo.value);
  }

  // 设置跳转连接参数
  function setIsWindow7(type: boolean) {
    isWindow7.value = type;
  }

  // 设置跳转连接参数
  function setLinkId(id: string) {
    linkId.value = id;
  }

  /**
   * 登录
   *
   * @param {LoginData}
   * @returns
   */
  function login(loginData: LoginData, rememberPsw: boolean) {
    return new Promise<void>((resolve, reject) => {
      loginApi(loginData)
        .then((response) => {
          token.value = JSON.stringify(response.data);
          if (rememberPsw) {
            // 过期时间为7年
            const date = new Date(
              new Date().getTime() + 7 * 365 * 24 * 60 * 60 * 1000
            );
            cookies.set("username", encrypt(loginData.username), {
              expires: date,
            });
            cookies.set("password", encrypt(loginData.password), {
              expires: date,
            });
          } else {
            cookies.remove("username");
            cookies.remove("password");
          }
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // 获取信息(用户昵称、头像、角色集合、权限集合)
  function getInfo() {
    return new Promise<UserInfo>((resolve, reject) => {
      getUserInfo()
        .then(({ data }) => {
          if (!data) {
            reject("校验失败，请重新登录");
            return;
          }
          const { userName, userType, userId, organizationId, parameters, loginName } = data;
          Object.assign(user, { ...user, userName, userType, userId, organizationId, parameters, loginName });
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // 获取按钮权限信息
  function getButtonPermission() {
    return new Promise<UserInfo>((resolve, reject) => {
      getButtonInfo()
        .then(({ data }) => {
          Object.assign(user, { ...user, perms: data });
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // 获取已读未读消息
  function getUnReadMessage() {
    return new Promise((resolve, reject) => {
      getUnReadMessageApi()
        .then(({ data }: any) => {
          unRead.value = Math.round(data);
          resolve(data);
        })
        .catch((error: any) => {
          reject(error);
        });
    });
  }

  // 注销
  function logout() {
    return new Promise<void>((resolve, reject) => {
      logoutApi()
        .then(() => {
          resetStore();
          location.reload(); // 清空路由
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  /** 清空缓存 */
  function resetStore() {
    resetRouter();
    token.value = "";
    Object.assign(user, {
      roles: [],
      perms: [],
      userName: "",
      userType: "",
      userId: "",
    });
  }
  return {
    token,
    unRead,
    user,
    linkId,
    isWindow7,
    userPlantInfo,
    setLinkId,
    setIsWindow7,
    login,
    getInfo,
    getButtonPermission,
    getUnReadMessage,
    logout,
    resetStore,
    setUserPlantInfo,
  };
});

// 非setup
export function useUserStoreHook() {
  return useUserStore(store);
}
